package com.lrkj.notice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lrkj.common.core.domain.entity.SysUser;
import com.lrkj.common.enums.NoticeType;
import com.lrkj.common.utils.DateUtils;
import com.lrkj.common.utils.SecurityUtils;
import com.lrkj.common.utils.StringUtils;
import com.lrkj.common.utils.uuid.IdUtils;
import com.lrkj.framework.websocket.WebSocketUtil;
import com.lrkj.framework.websocket.entity.WSMessage;
import com.lrkj.notice.domain.NoticeSiteMessage;
import com.lrkj.notice.domain.NoticeSiteMessageUser;
import com.lrkj.notice.mapper.NoticeSiteMessageMapper;
import com.lrkj.notice.service.INoticeSiteMessageService;
import com.lrkj.notice.service.INoticeSiteMessageUserService;
import com.lrkj.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 站内消息Service业务层处理
 *
 * @author yajun_ren
 * @date 2022-09-07
 */
@Service
public class NoticeSiteMessageServiceImpl implements INoticeSiteMessageService {
    @Autowired
    private NoticeSiteMessageMapper noticeSiteMessageMapper;

    @Autowired
    private INoticeSiteMessageUserService noticeSiteMessageUserService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询站内消息
     *
     * @param id 站内消息ID
     * @return 站内消息
     */
    @Override
    public NoticeSiteMessage selectNoticeSiteMessageById(String id) {
        return noticeSiteMessageMapper.selectNoticeSiteMessageById(id);
    }

    /**
     * 查询站内消息列表
     *
     * @param noticeSiteMessage 站内消息
     * @return 站内消息
     */
    @Override
    public List<NoticeSiteMessage> selectNoticeSiteMessageList(NoticeSiteMessage noticeSiteMessage) {
        return noticeSiteMessageMapper.selectNoticeSiteMessageList(noticeSiteMessage);
    }

    /**
     * 新增站内消息
     *
     * @param noticeSiteMessage 站内消息
     * @return 结果
     */
    @Override
    public int insertNoticeSiteMessage(NoticeSiteMessage noticeSiteMessage) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        noticeSiteMessage.setCreateTime(DateUtils.getNowDate());
        noticeSiteMessage.setId(IdUtils.simpleUUID());
        noticeSiteMessage.setSenderId(user.getUserId() + "");
        noticeSiteMessage.setMessageType(NoticeType.MESSAGE_TYPE_TZGG.getCode());
        this.setInfo(noticeSiteMessage);
        return noticeSiteMessageMapper.insertNoticeSiteMessage(noticeSiteMessage);
    }

    /**
     * 修改站内消息
     *
     * @param noticeSiteMessage 站内消息
     * @return 结果
     */
    @Override
    public int updateNoticeSiteMessage(NoticeSiteMessage noticeSiteMessage) {
        noticeSiteMessage.setUpdateTime(DateUtils.getNowDate());
        this.setInfo(noticeSiteMessage);
        return noticeSiteMessageMapper.updateNoticeSiteMessage(noticeSiteMessage);
    }

    public void setInfo(NoticeSiteMessage noticeSiteMessage) {
        if (StringUtils.isEmpty(noticeSiteMessage.getSendState())) {
            noticeSiteMessage.setSendState(NoticeType.SEND_STATE_10.getCode());
        }
    }

    /**
     * 批量删除站内消息
     *
     * @param ids 需要删除的站内消息ID
     * @return 结果
     */
    @Override
    public int deleteNoticeSiteMessageByIds(String[] ids) {
        return noticeSiteMessageMapper.deleteNoticeSiteMessageByIds(ids);
    }

    /**
     * 删除站内消息信息
     *
     * @param id 站内消息ID
     * @return 结果
     */
    @Override
    public int deleteNoticeSiteMessageById(String id) {
        return noticeSiteMessageMapper.deleteNoticeSiteMessageById(id);
    }

    @Override
    //批量更新发布状态
    public int msgPublish(String[] ids, String sendState) {
        String username = SecurityUtils.getUsername();
        NoticeSiteMessage eg = new NoticeSiteMessage();
        eg.getParams().put("ids", ids);
        List<NoticeSiteMessage> noticeSiteMessages = noticeSiteMessageMapper.selectNoticeSiteMessageList(eg);
        List<NoticeSiteMessageUser> saveNoticeUserBeans = new ArrayList<>();
        noticeSiteMessages.stream().forEach(x -> {
            x.setSenderName(username);
            x.setSenderTime(DateUtils.getNowDate());
            x.setSendState(sendState);
            x.setUpdateTime(DateUtils.getNowDate());
            x.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            if (sendState.equals(NoticeType.SEND_STATE_20.getCode())) {
                if (StringUtils.isNotEmpty(x.getUserIds()) && x.getReceiveType().equals(NoticeType.RECEIVE_TYPE_USER.getCode())) {
                    String[] userIds = x.getUserIds().split(",");
                    for (String userId : userIds) {
                        NoticeSiteMessageUser saveBean = new NoticeSiteMessageUser();
                        saveBean.setId(IdUtils.simpleUUID());
                        saveBean.setMessageId(x.getId());
                        saveBean.setReceiveId(userId);
                        saveBean.setHaveRead(NoticeType.HAVE_READ_10.getCode());
                        saveBean.setCreateTime(DateUtils.getNowDate());
                        saveNoticeUserBeans.add(saveBean);
                        if (!username.equals(userId)) {
                            WebSocketUtil.sendMessageTo(userId, WSMessage.getPcWSMessage(NoticeType.NOTICE_KEY_SYS_NOTICE.getCode(), this.noticeMsg(x, saveBean)));
                        }
                    }
                } else {
                    List<SysUser> sysUsers = sysUserService.selectUserList(new SysUser());
                    sysUsers.stream().forEach(user -> {
                        NoticeSiteMessageUser saveBean = new NoticeSiteMessageUser();
                        saveBean.setId(IdUtils.simpleUUID());
                        saveBean.setMessageId(x.getId());
                        saveBean.setReceiveId(user.getUserName());
                        saveBean.setHaveRead(NoticeType.HAVE_READ_10.getCode());
                        saveBean.setCreateTime(DateUtils.getNowDate());
                        saveNoticeUserBeans.add(saveBean);
                        if (!username.equals(user.getUserName())) {
                            WebSocketUtil.sendMessageTo(user.getUserName(), WSMessage.getPcWSMessage(NoticeType.NOTICE_KEY_SYS_NOTICE.getCode(), this.noticeMsg(x, saveBean)));
                        }
                    });
                }
            } else if (sendState.equals(NoticeType.SEND_STATE_30.getCode())) {

                if (StringUtils.isNotEmpty(x.getUserIds()) && x.getReceiveType().equals(NoticeType.RECEIVE_TYPE_USER.getCode())) {
                    String[] userIds = x.getUserIds().split(",");
                    for (String userId : userIds) {
                        if (!username.equals(userId)) {
                            WebSocketUtil.sendMessageTo(userId, WSMessage.getPcWSMessage(NoticeType.NOTICE_KEY_MSG_RECALL.getCode(),""));
                        }
                    }
                } else {
                    List<SysUser> sysUsers = sysUserService.selectUserList(new SysUser());
                    sysUsers.stream().forEach(user -> {
                        if (!username.equals(user.getUserName())) {
                            WebSocketUtil.sendMessageTo(user.getUserName(), WSMessage.getPcWSMessage(NoticeType.NOTICE_KEY_MSG_RECALL.getCode(),""));
                        }
                    });
                }
                x.setCancelTime(DateUtils.getNowDate());//撤回时间
                noticeSiteMessageUserService.deleteByMessageId(x.getId());//根据消息ID删除   用户关联消息
            }
        });
        if (noticeSiteMessages.size() > 0) {
            noticeSiteMessageMapper.batchUpdateSendState(noticeSiteMessages);
        }
        if (saveNoticeUserBeans.size() > 0) {
            //新增消息关联用户
            noticeSiteMessageUserService.doSaveList(saveNoticeUserBeans);
        }
        return 1;
    }

    //消息通知
    public String noticeMsg(NoticeSiteMessage message, NoticeSiteMessageUser messageUser) {
        JSONObject msg = new JSONObject();
        msg.put("title", message.getTitle());
        msg.put("content", message.getTitle());
        msg.put("senderName", message.getSenderName());
        msg.put("senderTime", message.getSenderTime());
        msg.put("messageUserId", messageUser.getId());
        msg.put("messageId", message.getId());
        msg.put("messageType",message.getMessageType());
        return msg.toJSONString();
    }

    /**
     * 批量新增站内消息信息
     *
     * @param noticeSiteMessages 站内消息对象
     */
    public int batchAddData(List<NoticeSiteMessage> noticeSiteMessages) {
        return noticeSiteMessageMapper.batchAddData(noticeSiteMessages);
    }
}
